package com.estate.web.controller.eastate;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.support.CaptchaType;
import com.estate.common.constant.ShiroConstants;
import com.estate.common.utils.ServletUtils;
import com.estate.common.utils.ShiroUtils;
import com.estate.common.utils.StringUtils;
import com.estate.common.utils.redis.RedisUtil;
import com.estate.common.utils.uuid.UUID;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.estate.common.annotation.Log;
import com.estate.common.enums.BusinessType;
import com.estate.system.domain.Regislatorbuyorsellorsell;
import com.estate.system.service.IRegislatorbuyorsellorsellService;
import com.estate.common.core.controller.BaseController;
import com.estate.common.core.domain.AjaxResult;
import com.estate.common.utils.poi.ExcelUtil;
import com.estate.common.core.page.TableDataInfo;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 【请填写功能名称】Controller
 * 
 * @author estate
 * @date 2022-07-07
 */
@Controller
@RequestMapping("/system/regislatorbuyorsellorsell")
@CrossOrigin
public class RegislatorbuyorsellorsellController extends BaseController
{
    private String prefix = "system/regislatorbuyorsellorsell";

    @Autowired
    private IRegislatorbuyorsellorsellService regislatorbuyorsellorsellService;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    @Resource
    RedisTemplate redisTemplate;

    @RequiresPermissions("system:regislatorbuyorsellorsell:view")
    @GetMapping()
    public String regislatorbuyorsellorsell()
    {
        return prefix + "/regislatorbuyorsellorsell";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:regislatorbuyorsellorsell:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Regislatorbuyorsellorsell regislatorbuyorsellorsell)
    {
        startPage();
        List<Regislatorbuyorsellorsell> list = regislatorbuyorsellorsellService.selectRegislatorbuyorsellorsellList(regislatorbuyorsellorsell);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:regislatorbuyorsellorsell:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Regislatorbuyorsellorsell regislatorbuyorsellorsell)
    {
        List<Regislatorbuyorsellorsell> list = regislatorbuyorsellorsellService.selectRegislatorbuyorsellorsellList(regislatorbuyorsellorsell);
        ExcelUtil<Regislatorbuyorsellorsell> util = new ExcelUtil<Regislatorbuyorsellorsell>(Regislatorbuyorsellorsell.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */

    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Regislatorbuyorsellorsell regislatorbuyorsellorsell)
    {
        return toAjax(regislatorbuyorsellorsellService.insertRegislatorbuyorsellorsell(regislatorbuyorsellorsell));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:regislatorbuyorsellorsell:edit")
    @GetMapping("/edit/{name}")
    public String edit(@PathVariable("name") String name, ModelMap mmap)
    {
        Regislatorbuyorsellorsell regislatorbuyorsellorsell = regislatorbuyorsellorsellService.selectRegislatorbuyorsellorsellByName(name);
        mmap.put("regislatorbuyorsellorsell", regislatorbuyorsellorsell);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:regislatorbuyorsellorsell:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Regislatorbuyorsellorsell regislatorbuyorsellorsell)
    {
        return toAjax(regislatorbuyorsellorsellService.updateRegislatorbuyorsellorsell(regislatorbuyorsellorsell));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:regislatorbuyorsellorsell:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(regislatorbuyorsellorsellService.deleteRegislatorbuyorsellorsellByNames(ids));
    }

        //得到验证码图片
    @GetMapping("/captcha")
    @ApiOperation(value = "登录模块生成验证码接口")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response){
        ServletOutputStream out = null;
        try
        {
            String token = UUID.randomUUID().toString();

            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            response.setHeader("Access-Control-Expose-Headers","Content-Type, Allow, Authorization, TOKEN");



            String type = request.getParameter("type");
            String capStr = null;
            String code = null;
            BufferedImage bi = null;
            if ("math".equals(type))
            {
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                bi = captchaProducerMath.createImage(capStr);
            }
            else if ("char".equals(type))
            {
                capStr = code = captchaProducer.createText();
                bi = captchaProducer.createImage(capStr);
            }
            //设置对应的token避免session不一致
            redisTemplate.opsForValue().set(token,code, Duration.ofSeconds(7200));
            response.setHeader("token",token);

            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

    //验证验证码
    @GetMapping("/verify")
    @ResponseBody
    public AjaxResult verify(HttpServletRequest request,String validateCode,String token){
        String authorization = (String)redisTemplate.opsForValue().get(token);
        if (authorization.length()!=0 && (authorization.equals(validateCode))){
            redisTemplate.opsForValue().set(token,null);


            return new AjaxResult().put("res","1");
        }
        // 校验通过
        return new AjaxResult().put("res","0");


    }
    /*
    * 将Session中存放的验证码清理掉，避免出现一次验证码多次使用的情况。
    *
    * */
    @GetMapping("/remove/captcha")
    public int removeCaptcha(HttpServletRequest request){

        HappyCaptcha.remove(request);
        return 1;
    }


}
